<template>
  <div>
    <header>
      <el-menu
        v-model:default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="index => (activeIndex = index)"
      >
        <el-menu-item index="1">全部项目</el-menu-item>
        <el-menu-item index="2">我负责的项目</el-menu-item>
        <el-menu-item index="3">我参与的项目</el-menu-item>
      </el-menu>
      <el-button class="btn-add" type="primary" @click="openAddProject"
        >项目立项</el-button
      >
    </header>
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 10px"
      row-key="id"
    >
      <el-table-column prop="name" label="项目名称" />

      <el-table-column prop="charge.nickName" label="负责人" />
      <el-table-column prop="beginTime" label="开始时间" />
      <el-table-column prop="endTime" label="结束时间" />
      <el-table-column prop="status" label="状态" width="100px">
        <template #default="scope">
          {{ projectStatus[scope.row.status - 1] }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" @click="openProjectDetails(scope.row.id)"
            >详情</el-button
          >
          <el-button type="warning" @click="openConclusion(scope.row.id)"
            >结题</el-button
          >
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            confirm-button-type="danger"
            title="是否确定删除项目"
            @confirm="deleteProjectFun(scope.row.id)"
          >
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 常规数据分页开始 -->
    <el-pagination
      v-model::current-page="query.current"
      v-model:page-size="query.size"
      style="margin-top: 10px"
      :total="pageTotal"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      layout="prev,pager,next,jumper,sizes,total"
      @size-change="pageSizeChange"
      @current-change="currPageChange"
    />
    <el-dialog
      v-model="addProjectDisplay"
      title="项目立项"
      width="500"
      destroy-on-close
    >
      <el-form label-width="auto" :model="projectForm" class="demo-form-inline">
        <el-form-item label="项目名称">
          <el-input
            v-model="projectForm.name"
            placeholder="请输入项目名称"
            clearable
            style="max-width: 240px"
          />
        </el-form-item>
        <el-form-item label="项目负责人">
          <user-selector v-model="projectForm.chargeId" />
        </el-form-item>
        <el-form-item label="项目计划日期">
          <el-date-picker
            v-model="projectForm.planTime"
            style="max-width: 240px"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="项目预估完成成本">
          <el-input-number v-model="projectForm.estimateCost" />
        </el-form-item>
        <div>
          <el-form-item label="项目成员">
            <user-selector v-model="projectForm.companyUserIds" multiple />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="项目描述">
            <el-input
              v-model="projectForm.description"
              style="max-width: 240px"
              type="textarea"
            />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="项目决议文件">
            <el-upload
              v-model:file-list="conferenceResolutionsFileList"
              :http-request="handleFileUpload"
              style="width: 240px"
              multiple
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="立项书文件">
            <el-upload
              v-model:file-list="projectPlanningPaperFileList"
              style="width: 240px"
              :http-request="handleFileUpload"
              multiple
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </div>

        <el-form-item label="项目进展状态">
          <el-select v-model="projectForm.status" style="max-width: 150px">
            <el-option
              v-for="(v, i) in projectStatus"
              :key="i"
              :value="i + 1"
              :label="v"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addProject"> 提交立项</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="detailsProjectDisplay"
      title="项目详情"
      width="500"
      destroy-on-close
    >
      <el-form label-width="auto" :model="projectForm" class="demo-form-inline">
        <el-form-item label="项目名称">
          <el-input
            v-model="projectForm.name"
            placeholder="请输入项目名称"
            clearable
            style="max-width: 240px"
          />
        </el-form-item>
        <el-form-item label="项目负责人">
          <user-selector v-model="projectForm.chargeId" />
        </el-form-item>
        <el-form-item label="项目计划日期">
          <el-date-picker
            v-model="projectForm.planTime"
            style="max-width: 240px"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="项目预估完成成本">
          <el-input-number v-model="projectForm.estimateCost" />
        </el-form-item>
        <div>
          <el-form-item label="项目成员">
            <user-selector v-model="projectForm.companyUserIds" multiple />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="项目描述">
            <el-input
              v-model="projectForm.description"
              style="max-width: 240px"
              type="textarea"
            />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="项目决议文件">
            <el-upload
              v-model:file-list="conferenceResolutionsFileList"
              :http-request="handleFileUpload"
              style="width: 240px"
              multiple
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="立项书文件">
            <el-upload
              v-model:file-list="projectPlanningPaperFileList"
              style="width: 240px"
              :http-request="handleFileUpload"
              multiple
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </div>

        <el-form-item label="项目进展状态">
          <el-select v-model="projectForm.status" style="max-width: 150px">
            <el-option
              v-for="(v, i) in projectStatus"
              :key="i"
              :value="i + 1"
              :label="v"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="updateProjectFun">修改</el-button>
          <el-button type="primary" @click="detailsProjectDisplay = false"
            >取消</el-button
          >
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="conclusionDetailsDisplay"
      :title="`项目结题${conclusionDisable ? '(已结题)' : ''}`"
      width="500"
      destroy-on-close
    >
      <el-form
        label-width="auto"
        :model="conclusionProjectForm"
        class="demo-form-inline"
      >
        <el-form-item label="项目名称">
          <project-selector
            v-model="conclusionProjectForm.projectId"
            disabled
          />
        </el-form-item>
        <el-form-item label="申请人">
          <user-selector
            v-model="conclusionProjectForm.applyCompanyUserId"
            :disabled="conclusionDisable"
          />
        </el-form-item>
        <el-form-item label="项目法人">
          <user-selector
            v-model="conclusionProjectForm.legalPersonId"
            :disabled="conclusionDisable"
          />
        </el-form-item>
        <el-form-item label="项目成果">
          <el-input
            v-model="conclusionProjectForm.projectOutcome"
            type="textarea"
            :disabled="conclusionDisable"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="相关文档">
          <el-upload
            v-model:file-list="conclusionFileList"
            :disabled="conclusionDisable"
            :http-request="handleConclusionFileUpload"
            style="width: 240px"
            multiple
          >
            <el-button :disabled="conclusionDisable" type="primary"
              >点击上传</el-button
            >
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            :disabled="conclusionDisable"
            type="primary"
            @click="conclusionProjectFun"
            >结题</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import {
  allProject,
  conclusionDetails,
  conclusionProject,
  deleteProject,
  initProject,
  myProject,
  projectDetails,
  submitProject,
  updateProject
} from "@/api/project.ts";
import { projectStatus } from "@/constants/project.ts";
import UserSelector from "@/components/Selector/UserSelector.vue";
import { uploadFile } from "@/api/file.ts";
import { ElMessage } from "element-plus";
import { stdTime } from "@/utils/time.ts";
import type { PageVoProjectListVo } from "@/api/models";
import { Result } from "@/api/common.ts";
import ProjectSelector from "@/components/Selector/ProjectSelector.vue";

defineOptions({
  name: "projectOverview"
});
let activeIndex = ref("1");
let tableData = ref([]);
let query = reactive({ current: 1, size: 10, keyword: "" });
let pageTotal = ref<number>(0);
async function getList() {
  let res: Result<PageVoProjectListVo>;
  switch (activeIndex.value) {
    case "1":
      res = await allProject(query.current, query.size, query.keyword);
      break;
    case "2":
      res = await myProject(query.keyword, query.current, query.size, true);
      break;
    case "3":
      res = await myProject(query.keyword, query.current, query.size, false);
      break;
  }
  if (res) {
    tableData.value = res.data.records;
    pageTotal.value = res.data.total;
  }
}
function pageSizeChange(pageSize) {
  query.size = pageSize;
  query.current = 1;
  getList();
}
// 数据页码变化
function currPageChange(pageIndex) {
  query.current = pageIndex;
  getList();
}
watch(activeIndex, (nv, ov) => {
  getList();
});
onMounted(() => {
  getList();
});
let addProjectDisplay = ref(false);
let projectForm = ref({
  planTime: [],
  estimateCost: 0,
  status: 1
});
function openAddProject() {
  addProjectDisplay.value = true;
  projectForm.value = { planTime: [], estimateCost: 0, status: 1 };
  conferenceResolutionsFileList.value = [];
  projectPlanningPaperFileList.value = [];
}
async function addProject() {
  let projectId = cacheProjectId.value
    ? cacheProjectId.value
    : (await initProject()).data.id;
  let planTime = projectForm.value.planTime.map(stdTime);
  let res = await submitProject({
    ...projectForm.value,
    id: projectId,
    conferenceResolutions: conferenceResolutionsFileList.value.map(
      ({ url, name }) => ({ url, filename: name })
    ),
    projectPlanningPaper: projectPlanningPaperFileList.value.map(
      ({ url, name }) => ({ url, filename: name })
    ),
    beginTime: planTime[0],
    endTime: planTime[1]
  });
  if (res.code == 200) {
    ElMessage({
      message: "立项成功",
      type: "success"
    });
    addProjectDisplay.value = false;
    await getList();
  } else {
    ElMessage({
      message: res.msg,
      type: "error"
    });
  }
}
let conferenceResolutionsFileList = ref([]);
let projectPlanningPaperFileList = ref([]);
let cacheProjectId = ref("");
async function handleFileUpload(file) {
  let res = await uploadFile(file.file);
  if (res.code === 200) {
    for (let item of conferenceResolutionsFileList.value) {
      if (item.uid == file.file.uid) {
        item.url = res.data.url;
      }
    }
    for (let item of projectPlanningPaperFileList.value) {
      if (item.uid == file.file.uid) {
        item.url = res.data.url;
      }
    }
  }
}
async function handleConclusionFileUpload(file) {
  let res = await uploadFile(file.file);
  if (res.code === 200) {
    for (let item of conclusionFileList.value) {
      if (item.uid == file.file.uid) {
        item.url = res.data.url;
      }
    }
  }
}

let detailsProjectDisplay = ref(false);
let projectUpdateVar = {
  companyUserAddIds: [],
  companyUserDeleteIds: [],
  conferenceResolutionsAdd: [],
  conferenceResolutionsDeleteIds: [],
  projectPlanningPaperAdd: [],
  projectPlanningPaperDeleteIds: []
};
async function openProjectDetails(id) {
  let res = await projectDetails(id);
  projectForm.value = {
    ...res.data,
    chargeId: res.data.charge.id,
    companyUserIds: res.data.companyUsers.map(i => i.id),
    planTime: [res.data.beginTime, res.data.endTime],
    id
  };
  conferenceResolutionsFileList.value = res.data.conferenceResolutions;
  projectPlanningPaperFileList.value = res.data.projectPlanningPaper;
  projectUpdateVar = {
    companyUserAddIds: [],
    companyUserDeleteIds: [],
    conferenceResolutionsAdd: [],
    conferenceResolutionsDeleteIds: [],
    projectPlanningPaperAdd: [],
    projectPlanningPaperDeleteIds: []
  };
  detailsProjectDisplay.value = true;
}
async function updateProjectFun() {
  let planTime = projectForm.value.planTime.map(stdTime);
  let res = await updateProject({
    ...projectForm.value,
    beginTime: planTime[0],
    endTime: planTime[1]
  });
  if (res.code == 200) {
    ElMessage({
      type: "success",
      message: "修改成功"
    });
    detailsProjectDisplay.value = false;
    getList();
  } else {
    ElMessage({
      type: "error",
      message: res.msg
    });
  }
}
async function deleteProjectFun(projectId) {
  let res = await deleteProject(projectId);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功"
    });
    await getList();
  } else {
    ElMessage({
      type: "error",
      message: res.msg
    });
  }
}
let conclusionDetailsDisplay = ref(false);
let conclusionDisable = ref(true);
async function openConclusion(projectId: number) {
  let res = await conclusionDetails(projectId);
  if (res.code !== 200) {
    ElMessage({
      type: "error",
      message: res.msg
    });
  } else if (res.data) {
    conclusionProjectForm.value = {
      projectId: projectId,
      legalPersonId: res.data.legalPerson.id,
      applyCompanyUserId: res.data.applyCompanyUser.id,
      projectOutcome: res.data.projectOutcome
    };
    conclusionFileList.value = res.data.conclusionFiles;
    conclusionDetailsDisplay.value = true;
    conclusionDisable.value = true;
  } else {
    conclusionProjectForm.value = {
      projectId: projectId,
      legalPersonId: 0,
      applyCompanyUserId: 0,
      projectOutcome: ""
    };
    conclusionDetailsDisplay.value = true;
    conclusionDisable.value = false;
    conclusionFileList.value = [];
  }
}
let conclusionProjectForm = ref({
  projectId: 0,
  legalPersonId: 0,
  applyCompanyUserId: 0,
  projectOutcome: ""
});
let conclusionFileList = ref([]);

async function conclusionProjectFun() {
  let res = await conclusionProject({
    ...conclusionProjectForm.value,
    conclusionFiles: conclusionFileList.value.map(({ url, name }) => ({
      url,
      filename: name
    }))
  });
  if (res.code !== 200) {
    ElMessage({
      type: "error",
      message: res.msg
    });
  } else {
    ElMessage({
      type: "success",
      message: "结题成功"
    });
    conclusionDetailsDisplay.value = false;
  }
}
</script>
<style lang="scss" scoped>
header {
  position: relative;

  .btn-add {
    position: absolute;
    top: 50%;
    right: 0;
    transform: translateY(-50%);
  }
}
</style>
